package com.ld.common.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.ld.shieldsb.annotation.Transaction;
import com.ld.shieldsb.dao.TransactionManager;

import lombok.extern.slf4j.Slf4j;

/**
 * 事务处理切面
 *
 * @author hansai
 * @date 2019-03-29
 */
@Aspect
@Component
@Slf4j
public class TransactionAspect {

    /**
     * 定义切入点
     */
    @Pointcut("@annotation(transaction)")
    public void doPointCut(Transaction transaction) {

    }

    /**
     * 通过连接点切入
     *
     * @param joinPoint
     * @param transaction
     * @return
     * @throws Exception
     */
    @Around("@annotation(transaction)")
    public Object doAround(ProceedingJoinPoint joinPoint, Transaction transaction) throws Exception {

        // 是否已经处在事务中
        boolean isInTransaction = TransactionManager.inTrans();
        if (!isInTransaction) {
            log.warn("aop 加入事务");
            try {
                // 事务开始
                TransactionManager.start();
                Object obj = joinPoint.proceed();
                // 提交事务
                TransactionManager.commit();
                return obj;
            } catch (Throwable throwable) {
                log.debug("捕获到事务异常！", throwable);
                TransactionManager.rollback();
                throw new Exception(throwable.getMessage());
            }
        } else {
            log.warn("aop 当前已处在事务中");
            try {
                // 执行方法
                return joinPoint.proceed();
            } catch (Throwable throwable) {
                throw new Exception(throwable);
            }
        }

    }

}
